package com.binfoo.www.apk;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;


/**
 * Created by ZhangHongbin on 2016/11/2.
 */
public class UpdateHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {

        // 读取收到的数据

        ByteBuf buf = packet.copy().content();

        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);

        String body = new String(req, CharsetUtil.UTF_8);

        System.out.println("【NOTE】>>>>>> 收到客户端的数据：" + body);

        String rsp = rspBean(body);

        System.out.println(rsp);

        // 回复一条信息给客户端
        ctx.writeAndFlush(new DatagramPacket(

                Unpooled.copiedBuffer(rsp, CharsetUtil.UTF_8), packet.sender())).sync();

    }

    public static String rspBean(String reqBean) {

        RequestBean req = JSON.parseObject(reqBean, RequestBean.class);

        System.out.println(req.toString());

        ResponseBean rsp = new ResponseBean();

        rsp.setFile_name("test.txt");
        rsp.setUpdate(true);
        rsp.setUpdate_log("update apk of 冠林");
        rsp.setUpdate_url("http://www.landleafservice.cn:9080/bms/sysuser/download?name=");
        rsp.setUpdate_type(0);
        rsp.setNew_version("V1.0.1");


        return JSON.toJSONString(rsp);
    }

}
